package homework.six.UDP;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class Client {
    public static void main(String[] args) {
        try {
            // 创建发送方套接字，IP默认本地，端口号随机
            DatagramSocket sendSocket = new DatagramSocket();
            String mes = "hello world!";
            // 转换成字节放进packet里
            byte[] buf = mes.getBytes();
            //端口8888，IP本机地址
            int port = 8001;
            InetAddress ip = InetAddress.getLocalHost();
            //创建数据报
            DatagramPacket sendPacket = new DatagramPacket(buf, buf.length, ip, port);
            //套接字发送数据
            sendSocket.send(sendPacket);
            //接受反馈数据的缓冲存储器
            byte[] getBuf = new byte[1024];
            //接受反馈数据的数据报
            DatagramPacket getPacket = new DatagramPacket(getBuf, getBuf.length);
            sendSocket.receive(getPacket);
            //解析反馈信息
            String backMes = new String(getBuf, 0, getPacket.getLength());
            System.out.println("接收方返回的信息：" + backMes);
            //关闭套接字
            sendSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
